/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import modelo.UrgenciasTableModel;
import persistencia.PacientesDAO;
import persistencia.UrgenciasDAO;
import pojos.Urgencias;

/**
 *
 * @author dam2A
 */
public class PanelUrgencias extends javax.swing.JPanel {

    /**
     * Creates new form PanelUrgencias
     */
    UrgenciasDAO urgDAO = new UrgenciasDAO();
    List<String> nomcols = new LinkedList();
    VentanaPrincipal vp;
    PacientesDAO pDAO = new PacientesDAO();

    public PanelUrgencias(JFrame ventanaPadre) {
        initComponents();
        
        rellenarColumnas();
        rellenarComboBoxUrgencias();
        

    }
    
    private void rellenarComboBoxUrgencias() {
        List<Integer> listaCodigos = this.urgDAO.getCodigosUrgencias();

        DefaultComboBoxModel modeloCodUrgencias = new DefaultComboBoxModel();

        for (int i = 0; i < listaCodigos.size(); i++) {
           modeloCodUrgencias.addElement(listaCodigos.get(i));

        }

        this.cbxCodUrgencias.setModel(modeloCodUrgencias);
    }
     private void rellenarColumnas() {
        
        this.nomcols.add("idUrgencia");
        this.nomcols.add("fechaUrgencia");
        this.nomcols.add("fechaAlta");
        this.nomcols.add("idPA");
    }
     
     private void realizarBusqueda() throws ParseException {
        boolean checkCodUrgencia = this.selectCodigoUrgencia.isSelected();
        boolean checkFecha = this.selectFecha.isSelected();
        Integer codUrgencia = (Integer) this.cbxCodUrgencias.getSelectedItem();
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
        Date fecha = formatter.parse(dcFecha.getText());
        List<Urgencias> listaUrgencias;

        if (checkCodUrgencia && checkFecha) {
            listaUrgencias = this.urgDAO.getUrgenciaPorIdYFecha(codUrgencia, fecha);
        } else if (checkCodUrgencia && !checkFecha) {
            listaUrgencias = this.urgDAO.getUrgenciaporId(codUrgencia);
        } else if (!checkCodUrgencia && checkFecha) {
            listaUrgencias = this.urgDAO.getUrgenciasPorfecha(fecha);
        } else {
            listaUrgencias = this.urgDAO.getUrgenciasDani();
        }

        this.jTableUrgencias.setModel(new UrgenciasTableModel(nomcols,listaUrgencias));
    }
     
     
     private void modificarUrgencia() {
        int registroSeleccionado = this.jTableUrgencias.getSelectedRow();

        if (registroSeleccionado != -1) {

            //COGEMOS EL CODIGO DEL PEDIDO A RECEPCIONAR
            Integer codUrgenciaModificar = (Integer) this.jTableUrgencias.getValueAt(registroSeleccionado, 0);
            Urgencias urgenciaModificar = this.urgDAO.getUrgenciaporId(codUrgenciaModificar).get(0);
            JDialogModUrgencia jdModificarUrgencia = new JDialogModUrgencia(this, urgenciaModificar, urgDAO);
            jdModificarUrgencia.setVisible(true);

        } else {
            JOptionPane.showMessageDialog(this, "DEBES SELECCIONAR UNA URGENCIA DE LA TABLA PARA PODER MODIFICAR", "ERROR AL MODIFICAR", JOptionPane.ERROR_MESSAGE);
        }

    }
     
     
     private void eliminarUrgencia() throws ParseException {
        int registroSeleccionado = this.jTableUrgencias.getSelectedRow();

        if (registroSeleccionado != -1) {

            int opcion = JOptionPane.showConfirmDialog(this, "¿ESTAS SEGURO QUE DESEAS ELIMINAR ESTA URGENCIA?", "ELIMINAR URGENCIA", JOptionPane.INFORMATION_MESSAGE);

            if (opcion == JOptionPane.OK_OPTION) {
                Integer codUrgenciaEliminar = (Integer) this.jTableUrgencias.getValueAt(registroSeleccionado, 0);

                Urgencias urgenciaEliminar = this.urgDAO.getUrgenciaporId(codUrgenciaEliminar).get(0);
                this.urgDAO.eliminarUrgencia(urgenciaEliminar);

                JOptionPane.showMessageDialog(this, "LA URGENCIA HA SIDO ELIMINADA CON EXITO", "ELIMINACION COMPLETADA", JOptionPane.INFORMATION_MESSAGE);
                realizarBusqueda();
            }

        } else {
            JOptionPane.showMessageDialog(this, "DEBES SELECCIONAR UNA URGENCIA DE LA TABLA PARA PODER ELIMINARLO", "ERROR AL ELIMINAR", JOptionPane.ERROR_MESSAGE);
        }
    }
     private void refrescarComboBox() {
        this.cbxCodUrgencias.removeAllItems();
        rellenarComboBoxUrgencias();
    }
     
     
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jbAdd = new javax.swing.JButton();
        jbEdit = new javax.swing.JButton();
        jbDelete = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableUrgencias = new javax.swing.JTable();
        jPfiltros1 = new javax.swing.JPanel();
        selectCodigoUrgencia = new javax.swing.JCheckBox();
        cbxCodUrgencias = new javax.swing.JComboBox();
        selectFecha = new javax.swing.JCheckBox();
        dcFecha = new datechooser.beans.DateChooserCombo();

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jbAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_plus.png"))); // NOI18N
        jbAdd.setToolTipText("Insertar");
        jbAdd.setFocusable(false);
        jbAdd.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbAdd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAddActionPerformed(evt);
            }
        });
        jToolBar1.add(jbAdd);

        jbEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_edit2.png"))); // NOI18N
        jbEdit.setToolTipText("Modificar");
        jbEdit.setFocusable(false);
        jbEdit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbEdit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbEditActionPerformed(evt);
            }
        });
        jToolBar1.add(jbEdit);

        jbDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_cancel.png"))); // NOI18N
        jbDelete.setToolTipText("Borrar");
        jbDelete.setFocusable(false);
        jbDelete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbDelete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbDeleteActionPerformed(evt);
            }
        });
        jToolBar1.add(jbDelete);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_find.png"))); // NOI18N
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("                            URGENCIAS");
        jToolBar1.add(jLabel2);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Filtros de busqueda"));

        jTableUrgencias.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "IdUrgencia", "Fecha", "Fecha Alta", "ID PA"
            }
        ));
        jScrollPane1.setViewportView(jTableUrgencias);

        jPfiltros1.setBorder(javax.swing.BorderFactory.createTitledBorder("Filtros de Búsqueda"));
        jPfiltros1.setLayout(new java.awt.GridLayout(2, 2));

        selectCodigoUrgencia.setText("Codigo Urgencia");
        jPfiltros1.add(selectCodigoUrgencia);

        cbxCodUrgencias.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jPfiltros1.add(cbxCodUrgencias);

        selectFecha.setText("Fecha Urgencia");
        selectFecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectFechaActionPerformed(evt);
            }
        });
        jPfiltros1.add(selectFecha);

        dcFecha.setWeekStyle(datechooser.view.WeekDaysStyle.SHORT);
        dcFecha.setEnabled(false);
        dcFecha.setLocale(new java.util.Locale("es", "", ""));
        jPfiltros1.add(dcFecha);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 768, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(127, 127, 127)
                .addComponent(jPfiltros1, javax.swing.GroupLayout.PREFERRED_SIZE, 387, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addComponent(jPfiltros1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(61, 61, 61)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(87, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jbAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAddActionPerformed

        JDialogAddUrgencias jdu = new JDialogAddUrgencias(this);
        jdu.setVisible(true);
        refrescarComboBox();
    }//GEN-LAST:event_jbAddActionPerformed

    private void jbDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbDeleteActionPerformed
        try {
            eliminarUrgencia();
        } catch (ParseException ex) {
            Logger.getLogger(PanelUrgencias.class.getName()).log(Level.SEVERE, null, ex);
        }
       refrescarComboBox();
    }//GEN-LAST:event_jbDeleteActionPerformed

    private void jbEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbEditActionPerformed
        modificarUrgencia();
        try {
            realizarBusqueda();
        } catch (ParseException ex) {
            Logger.getLogger(PanelUrgencias.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jbEditActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            realizarBusqueda();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "No hay ninguna urgencia");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void selectFechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectFechaActionPerformed
        // TODO add your handling code here:
        
        this.dcFecha.setEnabled(!dcFecha.isEnabled());
    }//GEN-LAST:event_selectFechaActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cbxCodUrgencias;
    private datechooser.beans.DateChooserCombo dcFecha;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPfiltros1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableUrgencias;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton jbAdd;
    private javax.swing.JButton jbDelete;
    private javax.swing.JButton jbEdit;
    private javax.swing.JCheckBox selectCodigoUrgencia;
    private javax.swing.JCheckBox selectFecha;
    // End of variables declaration//GEN-END:variables
}
